package com.yazif.vqa.task.chain;

import com.yazif.vqa.api.wechat.domain.Message;
import com.yazif.vqa.dao.RedisDao;
import com.yazif.vqa.domain.MessageListEnum;
import com.yazif.vqa.domain.Pend;
import com.yazif.vqa.task.AbstractTarget;
import com.yazif.vqa.task.Target;
import com.yazif.vqa.util.MessageUtils;
import com.yazif.vqa.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
public class AnsTarget extends AbstractTarget {

    @Resource
    private RedisDao redisDao;

    @Override
    public Message execute(Message message, Target target) {
        if (!"TEXT".equals(message.getMsgType())) {
            return target.execute(message);
        }
        String user = message.getFromUserName();
        String imgUri = getStoredImgUri(user);
        if (StringUtils.isBlank(imgUri)) {
            return target.execute(message);
        }

        Message send = MessageUtils.getBaseRecvMessage(message);
        send.setMsgType("TEXT");

        String content = doAnsTarget(message, imgUri);
        send.setContent(content);
        return send;
    }

    private String doAnsTarget(Message message, String imgUri) {
        try {
            Pend pend = new Pend();
            pend.setFromUser(message.getFromUserName());
            pend.setToUser(message.getToUserName());
            pend.setImageUri(imgUri);
            pend.setQues(message.getContent());

            String k = RedisKeyUtil.getMessageList(MessageListEnum.PENDING);
            redisDao.lpush(k, pend);
        } catch (Exception e){
            return "出现异常，请重试";
        }
        return  "计算中，请稍后...";
    }

    private String getStoredImgUri(String user) {
        String key = RedisKeyUtil.getImageKey(user);
        return redisDao.get(key);
    }
}
